package com.shangxia.leetcode.greedyAlgorithm;

import lombok.extern.slf4j.Slf4j;

/**
 * @ProjectName: leetcode
 * @ClassName: CanPlaceFlowers605
 * @Time: 2020/12/6
 * @Author: zhouy
 * @Description: 605. 种花问题
 * @Experience:
 */

@Slf4j
public class CanPlaceFlowers605 {
    public static void main(String[] args) {
        System.out.println(canPlaceFlowers(new int[]{0,0,1,0,0},1));
    }

    public static boolean canPlaceFlowers(int[] flowerbed, int n) {
        int num = 0;
        if (n > flowerbed.length / 2 + 1) {
            return false;
        }
        if (flowerbed.length == 1) {
            if (flowerbed[0] == 0) {
                num = 1;
                return num >= n;
            }
        }
        if (flowerbed.length >= 2) {
            if (flowerbed[0] == 0 && flowerbed[1] == 0) {
                flowerbed[0] = 1;
                num++;
            }
        }
        for (int i = 1; i < flowerbed.length - 1; i++) {
            if (flowerbed[i - 1] == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
                num++;
                flowerbed[i] = 1;
            }
        }
        if (flowerbed.length > 2) {
            if (flowerbed[flowerbed.length - 2] == 0 && flowerbed[flowerbed.length - 1] == 0) {
                num++;
            }
        }
        return num >= n;
    }
    public static boolean canPlaceFlowers2(int[] flowerbed, int n) {
        int i = 0, count = 0;
        while (i < flowerbed.length) {
            if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
                flowerbed[i] = 1;
                count++;
            }
            i++;
        }
        return count >= n;
    }
}
